import {
	defineStore
} from 'pinia';

import {
	computed,
	ref
} from 'vue';


export const useCartStore = defineStore('m_cart', () => {
	const cart = ref([]);

	const addToCart = (goods) => {
		const findResult = cart.value.find((x) => {
			return x.goods_id === goods.goods_id
		})
		if (!findResult) {
			cart.value.push(goods)
		} else {
			findResult.goods_count++
		}
	}

	const total = computed(() => {
		let c = 0
		cart.value.forEach(goods => c += goods.goods_count)
		return c
	})

	const updateState = (goods) => {
		const findResult = cart.value.find(x => x.goods_id === goods.goods_id)
		if (findResult) {
			findResult.goods_state = goods.goods_state
		}
	}

	const updateGoodsCount = (goods) => {
		const findResult = cart.value.find(x => x.goods_id === goods.goods_id)
		if (findResult) {
			findResult.goods_count = goods.goods_count
		}
	}

	const removeGoodsById = (goods_id) => {
		cart.value = cart.value.filter(x => x.goods_id != goods_id)
	}

	const checkedCount = () => {
		return cart.value.filter(x => x.goods_state).reduce((t, item) => t += item.goods_count, 0)
	}

	const updateAllGoodsState = (newState) => {
		cart.value.forEach(x => x.goods_state = newState)
	}

	const checkedGoodsAmount = computed(
		() => {
			return cart.value.filter(x => x.goods_state).reduce((t, item) => t += item.goods_count * item
				.goods_price,
				0).toFixed(2)
		}
	)

	return {
		cart,
		addToCart,
		total,
		updateState,
		updateGoodsCount,
		removeGoodsById,
		checkedCount,
		updateAllGoodsState,
		checkedGoodsAmount
	};
}, {
	persist: {
		paths: ['m_cart'],
	},
});